<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Customer;
use App\Models\Address;
use App\Models\City;
use App\Models\Payment;
use App\Models\User;
use App\Models\Order;
use App\Models\SellerWithdrawRequest;

class CustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        \DB::enableQueryLog();
        $sort_search = null;
        $users = User::where('user_type', 'customer')
            ->when(in_array($request->input('is_virtual_user'), ['yes', 'no']), function($query) use($request) {
                return $query->where('is_virtual_user', $request->input('is_virtual_user') == 'yes' ? 1 : 0);
            })
            //->where('email_verified_at', '!=', null)
            ->orderBy('created_at', 'desc');
        if ($request->has('search')){
            $sort_search = $request->search;
            $users->where(function ($q) use ($sort_search){
                $q->where('name', 'like', '%'.$sort_search.'%')->orWhere('email', 'like', '%'.$sort_search.'%');
            });
        }
        $users = $users->paginate(15);
        $is_virtual_user = $request->input('is_virtual_user');
        $sql = \DB::getQueryLog();
        return view('backend.customer.customers.index', compact('users', 'sort_search', 'is_virtual_user', 'sql'));
    }
    
    public function withdraw_requests(Request $request)
    {
        $customer_withdraw_requests = SellerWithdrawRequest::where('user_type', 'customer')->latest()->paginate(15);
        return view('backend.customer.customers.withdraw_requests', compact('customer_withdraw_requests'));
    }
    
    public function payment_modal(Request $request)
    {
        $customer = User::findOrFail($request->id);
        $customer_withdraw_request = SellerWithdrawRequest::where('id', $request->customer_withdraw_request_id)->first();
        return view('backend.customer.customers.withdraw_request_payment_modal', compact('customer', 'customer_withdraw_request'));
    }
    
    public function payments_history(Request $request)
    {
        $payments = Payment::where('user_type', 'customer')->where('payment_method', '!=', 'topup')->latest()->paginate(15);
        return view('backend.customer.customers.payment_history', compact('payments'));
    }
    
    public function payments_detail(Request $request, string $id)
    {
        $payments = Payment::where('seller_id', decrypt($id))->where('user_type', 'customer')->latest()->get();
        if($payments->count() > 0){
            return view('backend.customer.customers.payment', compact('payments'));
        }
        flash(translate('No payment history available for this seller'))->warning();
        return back();
    }

    public function message_modal(Request $request)
    {
        $customer_withdraw_request = SellerWithdrawRequest::findOrFail($request->id);
        return view('backend.customer.customers.withdraw_request_message_modal', compact('customer_withdraw_request'));
    }
    
    public function create_virtual_user(Request $request)
    {
        try {
            \DB::beginTransaction();
            $max = \intval($request->input('max')) < 1 ? 1 : (\intval($request->input('max')) > 100 ? 100 : \intval($request->input('max'))); 
            for($i = 0; $i < $max; $i++) {
                $faker = \Faker\Factory::create();
                $city = City::skip(mt_rand(0, City::count() - 1))->take(1)->first();
                $user = new User();
                $user->name = $faker->name;
                $user->is_virtual_user = 1;
                //$user->password = bcrypt('test');
                $user->email = $faker->email;
                $user->email_verified_at = \date('Y-m-d H:i:s');
                $user->balance = \sprintf('%0.2f', $request->balance);
                $user->saveOrFail();
                
                $referred_by = User::where('id', $request->referred_by)->first();
                if ($referred_by) {
                    $user->referred_by = $request->referred_by;
                    $user->node = $referred_by->node .','.$user->id;
                    $user->deep = $referred_by->deep + 1;
                } else {
                    $user->node = $user->id;
                }
                $user->saveOrFail();
                
                $address = new Address();
                $address->user_id = $user->id;
                $address->country_id = $city->state->country->id;
                $address->state_id = $city->state->id;
                $address->city_id = $city->id;
                $address->address = $faker->address;
                $address->postal_code = $faker->postcode;
                $address->phone = $faker->e164PhoneNumber;
                $address->saveOrFail();
            }
            \DB::commit();
            return 1;
        }catch(\Throwable $ex) {
            \DB::rollBack();
            throw $ex;
        }
        return 0;
        
    }
    
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'          => 'required',
            'email'         => 'required|unique:users|email',
            'phone'         => 'required|unique:users',
        ]);
        
        $response['status'] = 'Error';
        
        $user = User::create($request->all());
        
        $customer = new Customer;
        
        $customer->user_id = $user->id;
        $customer->save();
        
        if (isset($user->id)) {
            $html = '';
            $html .= '<option value="">
                        '. translate("Walk In Customer") .'
                    </option>';
            foreach(Customer::all() as $key => $customer){
                if ($customer->user) {
                    $html .= '<option value="'.$customer->user->id.'" data-contact="'.$customer->user->email.'">
                                '.$customer->user->name.'
                            </option>';
                }
            }
            
            $response['status'] = 'Success';
            $response['html'] = $html;
        }
        
        echo json_encode($response);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        User::destroy($id);
        flash(translate('Customer has been deleted successfully'))->success();
        return redirect()->route('customers.index');
    }
    
    public function bulk_customer_delete(Request $request) {
        if($request->id) {
            foreach ($request->id as $customer_id) {
                $this->destroy($customer_id);
            }
        }
        
        return 1;
    }

    public function login($id)
    {
        $user = User::findOrFail(decrypt($id));

        auth()->login($user, true);

        return redirect()->route('dashboard');
    }

    public function ban($id) {
        $user = User::findOrFail(decrypt($id));

        if($user->banned == 1) {
            $user->banned = 0;
            flash(translate('Customer UnBanned Successfully'))->success();
        } else {
            $user->banned = 1;
            flash(translate('Customer Banned Successfully'))->success();
        }

        $user->save();
        
        return back();
    }
}
